package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.dao.TokenDao;
import com.lagou.edu.pojo.LAuthCode;
import com.lagou.edu.pojo.LToken;
import com.lagou.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private AuthCodeDao authCodeDao;
    @Autowired
    private TokenDao tokenDao;

    @Override
    public String login(String email, String password) {
        LAuthCode authCode = new LAuthCode();
        authCode.setEmail(email);
        authCode.setPassword(password);
        Example<LAuthCode> example = Example.of(authCode);
        Optional<LAuthCode> one = authCodeDao.findOne(example);
        if(!one.isEmpty()){
            LAuthCode lAuthCode = one.get();
            return lAuthCode.getEmail();
        }
        return "false";

    }

    @Override
    public boolean register(String email, String password, String code) {
        LAuthCode authCode = new LAuthCode();
        LAuthCode byEmail = findByEmail(email);
        if(null != byEmail){
            authCode.setId(byEmail.getId());
        }
        authCode.setState("0");
        authCode.setEmail(email);
        authCode.setPassword(password);
        authCode.setCode(code);

        authCodeDao.save(authCode);
        if(authCode.getId()>0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean isRegister(String email) {
        LAuthCode byEmail = findByEmail(email);
        if(null != byEmail){
            String state = byEmail.getState();
            if(null != state && "0".equals(state)){
                return true;
            }
        }
        return false;
    }

    public LAuthCode findByEmail(String email){
        LAuthCode lAuthCode = new LAuthCode();
        lAuthCode.setEmail(email);
        Example<LAuthCode> example = Example.of(lAuthCode);
        Optional<LAuthCode> one = authCodeDao.findOne(example);
        if(!one.isEmpty()){
            return one.get();
        }
        return null;
    }

    @Override
    public String getEmail(String token) {
        LToken lToken = new LToken();
        lToken.setToken(token);
        Example<LToken> example = Example.of(lToken);

        Optional<LToken> one = tokenDao.findOne(example);
        if(!one.isEmpty()){
            LToken lToken1 = one.get();
            return lToken1.getEmail();
        }
        return "false";
    }

    @Override
    public void saveToken(String email, String token){
        LToken lToken = new LToken();
        lToken.setEmail(email);
        lToken.setToken(token);
        tokenDao.save(lToken);
    }
}
